package com.groupbuying.payconsumer.mq;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.groupbuying.payconsumer.utils.JSONUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 支付回执统一处理监听
 *
 * @Author Vincentxin
 * @Date 2019-05-29
 */
@Component
public class PayResultListener implements MessageListener {
    public static final Logger LOGGER = LoggerFactory.getLogger(PayResultListener.class);
    @Autowired
    private AliPayResult aliPayResult;
    @Autowired
    private WeChatPayResult weChatPayResult;
    @Autowired
    private CurrencyPayResult currencyPayResult;
    @Autowired
    private YsPayResult ysPayResult;
    @Autowired
    private BalancePayResult balancePayResult;

    @Autowired
    private PayOrderStateConfirm payOrderStateConfirm;
    @Autowired
    private WeChatPayOrderStateConfirm weChatPayOrderStateConfirm;
    @Autowired
    private AliPayOrderStateConfirm aliPayOrderStateConfirm;
    @Autowired
    private BalancePayStateConfirm balancePayStateConfirm;
    @Autowired
    private CurrencyPayStateConfirm currencyPayStateConfirm;

    @Override
    public Action consume(Message message, ConsumeContext context) {
        //Topic校验Tag校验
        if (!message.getTopic().equals(PayMQConfig.TOPIC) || StringUtils.isEmpty(message.getTag())) {
            LOGGER.error("Topic不符合订阅要求，Topic：" + message.getTopic() + "或者Tag为空，Tag：" + message.getTag());
            return Action.CommitMessage;
        }
        //获取消息重试次数
        int reconsume = message.getReconsumeTimes();
        if (reconsume == 3 && !message.getTag().endsWith("TIMING")) {
            LOGGER.error("该消息重复消费三次，直接标识成功"+message.getTag());
            return Action.CommitMessage;

        }
        //解析消息体
        Map<String, Object> result = new HashMap<>();
        try {
            result = JSONUtils.jsonToMap(new String(message.getBody()));
        }catch (Exception e){
            e.printStackTrace();
        }
        /**
         * 通过TAG来判断处理方式
         * 备注：此处提现多态，可以使用策略来处理。
         */
        LOGGER.info("获取消息："+result.toString());
        boolean handleResult = true;
        boolean confirmResult = true;

        if (PayMQConfig.TAG_WX_PAYBACK.equals(message.getTag())) {
            //原生微信支付回执处理
            LOGGER.info("===========原生微信支付异步回执处理：============");
            handleResult = weChatPayResult.dealResult(result);

        } else if (PayMQConfig.TAG_YS_PAYBACK.equals(message.getTag())) {
            //银盛微信支付回执处理
            LOGGER.info("===========银盛微信支付异步回执处理：============");
            handleResult = ysPayResult.dealResult(result);

        } else if (PayMQConfig.TAG_CUR_PAYBACK.equals(message.getTag())) {
            //积分支付回执处理
            LOGGER.info("===========积分支付异步回执处理：============");
            handleResult = currencyPayResult.dealResult(result);

        } else if (PayMQConfig.TAG_BAL_PAYBACK.equals(message.getTag())) {
            //余额支付回执处理
            LOGGER.info("===========余额支付异步回执处理：============");
            handleResult = balancePayResult.dealResult(result);

        } else if (PayMQConfig.TAG_ALI_PAYBACK.equals(message.getTag())) {
            //TODO 原生支付宝支付回执处理
            LOGGER.info("===========原生支付宝支付异步回执处理：==========");
            handleResult = aliPayResult.dealResult(result);

        } else if (PayMQConfig.TAG_YS_ALI_PAYBACK.equals(message.getTag())){
            //银盛支付宝支付回执处理,直接使用银盛微信的回执处理方法，回执内容一致处理方式一致
            LOGGER.info("===========银盛支付宝支付异步回执处理：==========");
            handleResult = ysPayResult.dealResult(result);
            /**
             * 以下代码用于各个支付类型的自动检测支付结果设置
             */
        } else if (PayMQConfig.TAG_YS_TIMING.equals(message.getTag())){
            LOGGER.info("=====支付类型:{},支付单号：{},支付结果定时检查开始主动查询",message.getTag(),result.get("key"));
            confirmResult = payOrderStateConfirm.dealResult(result);
        }else if (PayMQConfig.TAG_WECHAT_TIMING.equals(message.getTag())){
            LOGGER.info("微信原生支付主动查询调用");
            confirmResult = weChatPayOrderStateConfirm.dealResult(result);
        }else if (PayMQConfig.TAG_ALI_TIMING.equals(message.getTag())){
            //TODO 此处写支付宝原生支付主动查询变更的逻辑
            LOGGER.info("支付宝原生支付主动查询调用");
            confirmResult = aliPayOrderStateConfirm.dealResult(result);
        }else if (PayMQConfig.TAG_BALANCE_TIMING.equals(message.getTag())){
            confirmResult = balancePayStateConfirm.dealResult(result);
            LOGGER.info("余额支付主动查询调用");
        }else if (PayMQConfig.TAG_CUR_TIMING.equals(message.getTag())){
            confirmResult = currencyPayStateConfirm.dealResult(result);
            LOGGER.info("积分支付主动查询调用");
        }
        //判断结果
        if (!handleResult) {
            LOGGER.error("异步回执处理失败；Tag：{}",message.getTag());
        }
        //主动查询检验
        if (!confirmResult && reconsume == 4){
            LOGGER.error("支付单结果验证处理失败；第三方支付单号：{},验证两次失败",result.get("key").toString());
            return Action.CommitMessage;
        }else if (!confirmResult){
            LOGGER.info("支付单结果验证处理第{}次失败,第三方支付单号{}",reconsume+1,result.get("key").toString());
            return Action.ReconsumeLater;
        }
        return Action.CommitMessage;

    }
}
